package com.offcn.web;

import com.offcn.domain.PageProduct;
import com.offcn.domain.Product;
import com.offcn.service.ProductService;
import com.offcn.service.impl.ProductServiceImpl;
import com.offcn.utils.BaseServlet;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@WebServlet(name = "ProductServlet",urlPatterns = "/productServlet")
public class ProductServlet extends BaseServlet {
    //依赖service层进行查询
    ProductService ps = new ProductServiceImpl();

    public String demo(HttpServletRequest request, HttpServletResponse response){
        return null;
    }
    public String findPageProduct(HttpServletRequest request, HttpServletResponse response)
    {
        //获取查询页数
        String number = request.getParameter("pageNumber");
        int pageNumber = 1;
        if (number!=null){
            pageNumber=Integer.parseInt(number);
        }
        //依赖service查询分页所有信息
        PageProduct pp = ps.findInfoPage(pageNumber);
        //把分页信息转发到request域对象
        request.setAttribute("pp",pp);
        return "page.jsp";

    }
    //根据id修改
    public String findProById(HttpServletRequest request, HttpServletResponse response){
        String pid = request.getParameter("pid");
        Product p = ps.findProsById(pid);
        request.setAttribute("pro",p);
        return "update.jsp";
    }
    //批量查询
    public String BatchDel(HttpServletRequest request, HttpServletResponse response){
        String[] pids = request.getParameterValues("pid");

        ps.BatchdelProduct(pids);
        return "productServlet?method=findAll";
    }
    //根据id删除
    public String delProById(HttpServletRequest request, HttpServletResponse response){
        String pid = request.getParameter("pid");
        ps.delProduct(pid);
        return "productServlet?method=findAll";
    }
    //查询所有商品
    public String findAll(HttpServletRequest request, HttpServletResponse response){
        //依赖service层查询
        List<Product> pros = ps.findPros();
        request.setAttribute("pros",pros);
        return "show.jsp";
    }
    //新增
    public String addProduct(HttpServletRequest request, HttpServletResponse response){
        Map<String, String[]> map = request.getParameterMap();
        Product product = new Product();
        try {
            BeanUtils.populate(product,map);
            product.setPid(UUID.randomUUID()+"");
            product.setPdate(new Date());
            boolean flag = ps.addProduct(product);
            if(flag) {
                //新增成功，再次查询所有商品
                return "productServlet?method=findAll";
            }else {
                //失败，继续新增
                return "add.jsp";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "productServlet?method=findAll";
    }
}
